package com.lishe.lishe.net;

import com.alipay.android.phone.mrpc.core.NetworkUtils;
import com.lishe.lishe.lishe.base.BaseApplication;
import com.lishe.lishe.lishe.utils.LogUtil;
import java.io.IOException;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author Created by Bin
 */

public class CacheInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        if(!NetworkUtils.isNetworkAvailable(BaseApplication.getContext().getApplicationContext())){
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
            LogUtil.d("CacheInterceptor","no network");
        }
        Response originalResponse = chain.proceed(request);

        if(NetworkUtils.isNetworkAvailable(BaseApplication.getContext().getApplicationContext())){
                String cacheControl = request.cacheControl().toString();
            //这里大家看点开源码看看.header .removeHeader做了什么操作很简答，就是的加字段和减字段的。
            return originalResponse.newBuilder()
                    //这里设置的为0就是说不进行缓存，我们也可以设置缓存时间
                    .header("Cache-Control", "public, max-age=" + 60*5)
                    .removeHeader("Pragma")
                    .build();
        }else{
            int maxTime = 4*24*60*60;
            return originalResponse.newBuilder()
                    //这里的设置的是我们的没有网络的缓存时间，想设置多少就是多少。
                    .header("Cache-Control", "public, only-if-cached, max-stale="+maxTime)
                    .removeHeader("Pragma")
                    .build();
        }

    }
}